package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yjj
 * @date 2021年09月19日 15:50
 * 因为继承了ServiceImpl，里面封装了Mapper，所以不用注入Mappertaining了
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;

    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildrenData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        //向List中每个对象中设置hashChildren
        for (Dict dict : dicts) {
            Long id1 = dict.getId();
            boolean b = this.idChildren(id1);
            dict.setHasChildren(b);
        }
        return dicts;
    }

    //导出
    @Override
    public void exprotDict(HttpServletResponse response) {


        //设置下载的信息
            //设置content类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");//编码
            //这里URLEncoder.encode可以防止中文乱码，当然和easyexcel没有关系
        String fileName = null;//文件名称
        try {
            fileName = URLEncoder.encode("数据字典","UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition","attachment;filename="+ fileName + ".xlsx");
        //查询数据库
            List<Dict> dicts = baseMapper.selectList(null);
            ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
            DictEeVo dictEeVo = null;
            for (Dict dict : dicts) {
                 dictEeVo = new DictEeVo();
                //把dict装换成dictVo
                BeanUtils.copyProperties(dict,dictEeVo,DictEeVo.class);
                dictEeVos.add(dictEeVo);
            }
            //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictEeVos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导入数据
    @Override
    @CacheEvict(value = "dict",allEntries = true) //数据发生改动，将会清空dict的数据
    public void importData(MultipartFile file){

        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper))
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //根据dictcode或者是value查询
    @Override
    public String getDictName(String dictcode, String value) {
        //如果dictcode为空，根据value查
        if (StringUtils.isEmpty(dictcode)){
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else {//如果dictcode不为空，则根据dictcode和value进行查询
            //根据dictcode查询出相应的dict的id
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code",dictcode);
            Dict codeDict = baseMapper.selectOne(wrapper);
            Long parentId = codeDict.getId();
            //根据parentId和value值进行查询
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parentId)
                    .eq("value", value));
            return dict.getName();
        }
    }

    //根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取对应的Id
        Dict dict = this.getDictByDictCode(dictCode);
        //根据id获取下级节点
        List<Dict> childrenData = this.findChildrenData(dict.getId());
        return childrenData;
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dicts = baseMapper.selectOne(wrapper);
        return dicts;
    }

    //判断Id下面是否有子数据
    public boolean idChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer integer = baseMapper.selectCount(wrapper);
        if (integer > 0 ){
            return true;
        }else {
            return false;
        }
    }




}
